package com.tinem.platform.web.netty.websocket.initializer;

import com.alibaba.fastjson.JSON;
import com.tinem.platform.module.pojo.enums.message.CommandEnum;
import com.tinem.platform.module.pojo.enums.message.Message;
import com.tinem.platform.web.netty.websocket.util.MessageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

/**
 * DiscardServerHandlerextends ChannelInboundHandlerAdapter，它是ChannelInboundHandler. ChannelInboundHandler提供了可以覆盖的各种事件处理程序方法。目前，扩展ChannelInboundHandlerAdapter而不是自己实现处理程序接口就足够了。
 * Handles a server-side channel.
 */
@Slf4j
@Service
@Scope("prototype")
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private WebSocketServerHandshaker handshaker;
    /**
     * 是否已经发送session 信息
     */
    private boolean isSessionMsg=false;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest){
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }else if (msg instanceof WebSocketFrame){
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx,msg);
        if(!isSessionMsg){
            isSessionMsg = true;
            MessageUtil.call(ctx, Message.builder().command(CommandEnum.session).build());
        }
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        Message message = Message.builder()
                .command(CommandEnum.close)
                .build();
        MessageUtil.call(ctx, message);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
        /**
         * 关闭socket
         */
        if (frame instanceof CloseWebSocketFrame) {
            //断开连接
            Message webSocketMessage = Message.builder()
                    .command(CommandEnum.close)
                    .build();
            MessageUtil.call(ctx, webSocketMessage);
            return;
        }

        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            log.info("未知消息:{}",frame.getClass().getName());
            return;
        }

        String com = ((TextWebSocketFrame) frame).text();
        log.debug("message：" + com);
        if(!JSON.isValid(com)){
            log.info("消息格式错误:{}",com);
            return;
        }
        Message webSocketMessage = JSON.parseObject(com,Message.class);
        if(webSocketMessage == null){
            return;
        }
        MessageUtil.call(ctx, webSocketMessage);
    }
    /**
     * 唯一的一次http请求，用于创建websocket
     * */
    private void handleHttpRequest(ChannelHandlerContext ctx,
                                   FullHttpRequest req) {
        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                null, null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }
    /**
     * 拒绝不合法的请求，并返回错误信息
     * */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
}